<template>
  <div v-if="hasPermission" class="permission-wrapper">
    <slot />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useAppStore } from '@/stores'

interface Props {
  // 菜单路径，如 '/cmdb/hosts'
  menuPath?: string
  // 权限类型：read | write | create | update | delete
  permission?: 'read' | 'write' | 'create' | 'update' | 'delete'
  // 是否需要所有权限（默认false，只需要其中一个）
  requireAll?: boolean
  // 多个菜单路径（用于复合权限检查）
  menuPaths?: string[]
  // 多个权限类型
  permissions?: ('read' | 'write' | 'create' | 'update' | 'delete')[]
  // 是否在无权限时隐藏（默认true），false时显示但禁用
  hideWhenNoPermission?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  permission: 'read',
  requireAll: false,
  hideWhenNoPermission: true,
  menuPaths: () => [],
  permissions: () => []
})

const appStore = useAppStore()

// 计算是否有权限
const hasPermission = computed(() => {
  // 超级管理员拥有所有权限
  if (appStore.userInfo?.is_superuser) {
    return true
  }

  // 简化版权限检查：如果是写权限，检查用户是否为管理员
  if (props.permission === 'write' || props.permission === 'create' ||
      props.permission === 'update' || props.permission === 'delete') {
    return appStore.userInfo?.is_staff || appStore.userInfo?.is_superuser || false
  }

  // 读权限默认允许已登录用户
  return !!appStore.userInfo
})

// 暴露权限状态给父组件
defineExpose({
  hasPermission
})
</script>

<style scoped>
.permission-wrapper {
  display: contents;
}
</style>
